package com.selune.online.ordering.system.common.component;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * Created with IntelliJ IDEA.
 *
 * @author xiaoyp
 * @date 2020/4/5
 * <p>
 * Description:
 */
@Component
@Slf4j
@ServerEndpoint("/webSocket")
public class WebSocketComponent {
	
	private Session session;
	
	/** 定义容器，储存session */
	private static CopyOnWriteArraySet<WebSocketComponent> webSocketSet = new CopyOnWriteArraySet<>();
	
	@OnOpen
	public void onOpen(Session session) {
		this.session = session;
		webSocketSet.add(this);
		log.info("【WebSocket消息】有新的连接，总数= {}", webSocketSet.size());
	}
	
	@OnClose
	public void onClose() {
		webSocketSet.remove(this);
		log.info("【WebSocket消息】连接断开，总数= {}", webSocketSet.size());
	}
	
	@OnMessage
	public void onMessage(String message) {
		log.info("【WebSocket消息】收到客户端发来的消息= {}", message);
	}
	
	public void sendMessage(String message) {
		for (WebSocketComponent webSocket : webSocketSet) {
			log.info("【WebSocket消息】广播消息， message= {}", message);
			try {
				webSocket.session.getBasicRemote().sendText(message);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
